package com.ysd.lis.service.lab.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.request.*;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.LabRptresultService;
import com.ysd.lis.service.lab.LabTemplateService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验模版 服务实现类
 * </p>
 *
 * @author HuiXing
 * @since 2024-01-02
 */
@Service
public class LabTemplateServiceImpl extends ServiceImpl<LabTemplateMapper, LabTemplate> implements LabTemplateService {

    @Autowired
    LabRptGroupMapper labRptGroupMapper;
    @Autowired
    LabTemplateMapper labTemplateMapper;
    @Autowired
    LabTemplateDetailMapper labTemplateDetailMapper;
    @Autowired
    LabRptresultService labRptresultService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    LabRptresultMapper labRptresultMapper;
    @Autowired
    LabItemDictMapper labItemDictMapper;
    @Autowired
    LabItemDictReferMapper labItemDictReferMapper;
    @Autowired
    SysParamValueService sysParamValueService;

    @Override
    public Result getRptGroupTree() {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);

        List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(lambdaQueryWrapper);

        List<Map> iList = new ArrayList<>();

        for (LabRptGroup labRptGroup : labRptGroups) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", labRptGroup.getId());
            map.put("name", labRptGroup.getRptGroupName());
            map.put("code", labRptGroup.getRptGroup());
            map.put("workGroup", labRptGroup.getWorkGroup());
            map.put("isSearch", "0");
            iList.add(map);
        }
        List<String> classList = labRptGroups.stream().map(LabRptGroup::getWorkGroup).distinct().collect(Collectors.toList());
        //查字典
        List<Map<String, Object>> yqdllist = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();

        //yqdllist = yqdllist.stream().filter(a -> a.get("name").equals("图文报告")).collect(Collectors.toList());

        List<Map> returnList = new ArrayList<>();
        for (int i = 0; i < classList.size(); i++) {
            String code = classList.get(i);

            List<Map<String, Object>> arr = yqdllist.stream().filter(a -> a.get("code").equals(code)).collect(Collectors.toList());

            List<Map> arr1 = iList.stream().filter(is -> is.get("workGroup") != null && is.get("workGroup").equals(code)).collect(Collectors.toList());

            Map<String, Object> map = new HashMap();
            map.put("id", i + 1);
            map.put("code", code);
            map.put("name", yqdllist.isEmpty() ? "" : arr.isEmpty() ? "" : arr.get(0).get("name"));
            try {
                map.put("sx", yqdllist.isEmpty() ? "" : arr.isEmpty() ? "999" : Integer.valueOf(String.valueOf(arr.get(0).get("sx"))));
            } catch (Exception e) {
                map.put("sx", 0);
            }
            map.put("children", arr1.isEmpty() ? new ArrayList<>() : arr1);
            map.put("isSearch", "1");
            returnList.add(map);
        }
        List<Map> newReturnList = returnList.stream().sorted(Comparator.comparing(l -> Integer.valueOf(String.valueOf(l.get("sx"))), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return Result.succ(1, "查询成功", newReturnList);
    }

    /**
     * 新增模版
     *
     * @param labTemplate
     * @return
     */
    @Override
    public Result addTemplate(LabTemplate labTemplate) {
        boolean save = this.save(labTemplate);
        if (save) {
            return Result.succ(1, "添加成功！", null);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result getTemplateByRptGroup(String rptGroup, String orgId, String searchValue) {
        MPJLambdaWrapper<LabTemplate> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabTemplate.class);
        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabTemplate::getSampleTypeNa);
        queryWrapper.eq(StringUtils.isNotBlank(orgId), LabTemplate::getOrgId, orgId);
        queryWrapper.like(StringUtils.isNotBlank(searchValue), LabTemplate::getTemplateName, searchValue);
        queryWrapper.eq(LabTemplate::getDelFlag, 0);
        queryWrapper.eq(LabTemplate::getRptGroup, rptGroup);
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabTemplate::getSampleType).eq(LabSampleType::getDelFlag, 0).isNotNull(LabSampleType::getSampleTypeCode).ne(LabSampleType::getSampleTypeCode, ""));
        queryWrapper.orderByAsc(LabTemplate::getSeq);

        List<LabTemplate> labTemplates = labTemplateMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", labTemplates);
    }

    @Override
    public Result getTemplateAndDetailByRptGroup(String rptGroup) {

        MPJLambdaWrapper<LabTemplate> qWrapper = new MPJLambdaWrapper<>();
        qWrapper.selectAll(LabTemplate.class);
        qWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabTemplate::getSampleTypeNa);
        qWrapper.eq(LabTemplate::getDelFlag, 0).eq(LabTemplate::getRptGroup, rptGroup);
        qWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabTemplate::getSampleType).eq(LabSampleType::getDelFlag, 0).isNotNull(LabSampleType::getSampleTypeCode).ne(LabSampleType::getSampleTypeCode, ""));
        qWrapper.orderByAsc(LabTemplate::getSeq);
        List<LabTemplate> labTemplates = labTemplateMapper.selectList(qWrapper);

        if (ToolsUtils.isNotEmpty(labTemplates)) {
            List<String> templateIds = labTemplates.stream().map(LabTemplate::getId).collect(Collectors.toList());
            LambdaQueryWrapper<LabTemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplateDetail::getDelFlag, 0).in(LabTemplateDetail::getTemplateId, templateIds);//p -> templateIds.contains(p.getTemplateId()));
            List<LabTemplateDetail> labTemplateDetails = labTemplateDetailMapper.selectList(queryWrapper);
            for (LabTemplate labTemplate : labTemplates) {
                labTemplate.setDetailList(labTemplateDetails.stream().filter(de -> de.getTemplateId().equals(labTemplate.getId())).collect(Collectors.toList()));
            }
        }
        return Result.succ(1, "查询成功", labTemplates);

    }


    @Override
    public Result findTemplates(Params params) {
        MPJLambdaWrapper<LabTemplate> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabTemplate.class);
        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabTemplate::getSampleTypeNa);
        queryWrapper.eq(LabTemplate::getDelFlag, 0);
        queryWrapper.like(LabTemplate::getTemplateCode, params.getSearchValue());
        queryWrapper.like(LabTemplate::getTemplateName, params.getSearchValue());
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabTemplate::getSampleType).eq(LabSampleType::getDelFlag, 0).isNotNull(LabSampleType::getSampleTypeCode).ne(LabSampleType::getSampleTypeCode, ""));
        queryWrapper.orderByAsc(LabTemplate::getSeq);
        List<LabTemplate> labTemplates = labTemplateMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", labTemplates);
    }

    /**
     * 批量删除
     *
     * @param dto
     * @return
     */
    @Override
    public Result batchDeleteTemplateList(TemplateDto dto) {
        List<LabTemplate> labTemplateList = dto.getLabTemplateList();
        List<String> ids = labTemplateList.stream().map(LabTemplate::getId).collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    /**
     * 编辑模版
     *
     * @param labTemplate
     * @return
     */
    @Override
    public Result editTemplate(LabTemplate labTemplate) {

        int i = labTemplateMapper.updateById(labTemplate);
        if (i > 0) {
            return Result.succ(1, "编辑成功！", null);
        } else {
            return Result.fail("编辑失败！");
        }
    }

    /**
     * @param params
     * @return
     */
    @Override
    @Transactional
    public Result batchInsertTemplateList(TemplateParams params) {
        //没有上机记录，先创建上机记录
//        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, params.getRptGroup());
//        lambdaQueryWrapper.eq(LabMaininfo::getSampleda, params.getSampleda());
//        lambdaQueryWrapper.eq(LabMaininfo::getSampleNo, params.getSampleNo());
//        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
//        if (!BeanUtil.isEmpty(params.getMaininfoId())) {
//            lambdaQueryWrapper.eq(LabMaininfo::getId, params.getMaininfoId());
//        }
//
//        //查询记录
//        List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
//        LabMaininfo lmiEntry = null;
//        if (labMainInfoList.isEmpty()) {
//            AddLabMaininfo labmi = new AddLabMaininfo();
//            labmi.setRptGroup(params.getRptGroup());
//            labmi.setSampleda(params.getSampleda());
//            labmi.setSampleNo(params.getSampleNo());
//            try {
//                LabMaininfo labMaininfo = new LabMaininfo();
//                BeanUtil.copyProperties(labmi,labMaininfo);
//                boolean save = labMaininfoService.save(labMaininfo);
//                lmiEntry = labMaininfo;
//
//            } catch (Exception e) {
//                //TODO
//            }
//        } else {
//            lmiEntry = (LabMaininfo) labMainInfoList.get(0);
//        }
//
//        if (BeanUtil.isEmpty(lmiEntry)) {
//            return Result.fail("没有要操作的检验记录");
//        }

//        if (BeanUtil.isEmpty(params.getMaininfoId())) {
//            params.setMaininfoId(lmiEntry.getId());
//        }
        List<LabRptresult> list = new ArrayList<>();

        List<String> templateIds = new ArrayList<>();
        if (!BeanUtil.isEmpty(params.getTemplateId())) {
            templateIds.add(params.getTemplateId());
        } else {
            LambdaQueryWrapper<LabTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplate::getDelFlag, 0).eq(LabTemplate::getRptGroup, params.getRptGroup()).eq(LabTemplate::getIsAutoApply, "1");
            List<LabTemplate> labTemplates = labTemplateMapper.selectList(queryWrapper);
            if (!labTemplates.isEmpty()) {
                for (LabTemplate m : labTemplates) {
                    templateIds.add(m.getId());
                }
            }
        }

        if (templateIds.isEmpty()) {
            return Result.succ(1, "添加成功", list);
        }

        LambdaQueryWrapper<LabTemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabTemplateDetail::getDelFlag, 0).in(LabTemplateDetail::getTemplateId, templateIds);//p -> templateIds.contains(p.getTemplateId()));
        List<LabTemplateDetail> labTemplateDetails = labTemplateDetailMapper.selectList(queryWrapper);

        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
        _labrptresultmapper.eq(LabRptresult::getMaininfoId, params.getMaininfoId());
        _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);

        //获取该报告单元下的所有的参考范围
        LambdaQueryWrapper<LabItemDictRefer> lambdaQueryWrapperRefer = new LambdaQueryWrapper<>();
        lambdaQueryWrapperRefer.eq(LabItemDictRefer::getRptGroup, params.getRptGroup()).eq(LabItemDictRefer::getDelFlag, 0);
        List<LabItemDictRefer> labItemDictRefers = labItemDictReferMapper.selectList(lambdaQueryWrapperRefer);


        for (LabTemplateDetail labTemplateDetail : labTemplateDetails) {
            /*待插入集合中中已有，直接跳过*/
            List<LabRptresult> _lst1 = list.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
            if (!_lst1.isEmpty()) {
                continue;
            }
            LabRptresult labRptresult = new LabRptresult();
            labRptresult.setSampleda(params.getSampleda());
            labRptresult.setRptGroup(params.getRptGroup());
            labRptresult.setSampleNo(params.getSampleNo());
            labRptresult.setMaininfoId(params.getMaininfoId());
            labRptresult.setItemNo(labTemplateDetail.getItemNo());
            labRptresult.setItemNa(labTemplateDetail.getItemNa());
            labRptresult.setTestResult(labTemplateDetail.getRptResult());
            labRptresult.setDisplayOrder(labTemplateDetail.getSeq());
            labRptresult.setOrgId(labTemplateDetail.getOrgId());
            labRptresult.setIsTemplateResult(1);

            Optional<LabItemDictRefer> first = labItemDictRefers.stream().filter(p -> p.getRptGroup().equals(params.getRptGroup()) && p.getItemNo().equals(labTemplateDetail.getItemNo())).findFirst();
            if (first.isPresent()) {
                labRptresult.setRef(first.get().getRange());
            }

            LambdaQueryWrapper<LabItemDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabItemDict::getItemNo, labTemplateDetail.getItemNo()).eq(LabItemDict::getRptGroup, params.getRptGroup()).eq(LabItemDict::getDelFlag, 0);
            List<LabItemDict> labItemDicts = labItemDictMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(labItemDicts)) {
                labRptresult.setItemDictId(labItemDicts.get(0).getId());
                labRptresult.setDisplayOrder(labItemDicts.get(0).getSeq() + "");
            }
            if (!rptresultlist.isEmpty()) {
                List<LabRptresult> _lst = rptresultlist.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
                if (_lst.isEmpty()) {
                    list.add(labRptresult);
                }
            } else {
                list.add(labRptresult);
            }
        }

        list = list.stream().sorted(Comparator.comparing(LabRptresult::getDisplayOrder)).collect(Collectors.toList());

//        boolean b = labRptresultService.saveBatch(list);
//        if (b) {
        return Result.succ(1, "添加成功", list);
//        } else {
//            return Result.fail("添加失败");
//        }

    }

    /**
     * @param params
     * @return
     */
    @Override
    public Result batchInsertDefItemDictAndTemplate(TemplateParams params) {
        //没有上机记录，先创建上机记录
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, params.getRptGroup());
        lambdaQueryWrapper.eq(LabMaininfo::getSampleda, params.getSampleda());
        lambdaQueryWrapper.eq(LabMaininfo::getSampleNo, params.getSampleNo());
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        if (!BeanUtil.isEmpty(params.getMaininfoId())) {
            lambdaQueryWrapper.eq(LabMaininfo::getId, params.getMaininfoId());
        }

        //查询记录
        List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
        LabMaininfo lmiEntry = null;
        if (labMainInfoList.isEmpty()) {
            AddLabMaininfo labmi = new AddLabMaininfo();
            labmi.setRptGroup(params.getRptGroup());
            labmi.setSampleda(params.getSampleda());
            labmi.setSampleNo(params.getSampleNo());
            try {
                Result r = labMaininfoService.insertMaininfoByReqNo(labmi);
                Integer c = (Integer) r.getStatus().get("code");
                if (!c.equals(1)) {
                    return Result.fail("新增检验记录失败");
                }
                lmiEntry = (LabMaininfo) r.getData();
            } catch (Exception e) {
                //TODO
            }
        } else {
            lmiEntry = (LabMaininfo) labMainInfoList.get(0);
        }

        if (BeanUtil.isEmpty(lmiEntry)) {
            return Result.fail("没有要操作的检验记录");
        }

        if (BeanUtil.isEmpty(params.getMaininfoId())) {
            params.setMaininfoId(lmiEntry.getId());
        }

        List<String> templateIds = new ArrayList<>();
        if (!BeanUtil.isEmpty(params.getTemplateId())) {
            templateIds.add(params.getTemplateId());
        } else {
            LambdaQueryWrapper<LabTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplate::getDelFlag, 0).eq(LabTemplate::getRptGroup, params.getRptGroup()).eq(LabTemplate::getIsAutoApply, "1");
            List<LabTemplate> labTemplates = labTemplateMapper.selectList(queryWrapper);
            if (!labTemplates.isEmpty()) {
                for (LabTemplate m : labTemplates) {
                    templateIds.add(m.getId());
                }
            }
        }

        if (templateIds.isEmpty() && StringUtils.isBlank(params.getReqNo())) {
            return Result.succ("添加成功");
        }
        List<LabRptresult> list = new ArrayList<>();

        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
        //_labrptresultmapper.eq(LabRptresult::getMaininfoId, lmiEntry.getId());
        _labrptresultmapper.eq(LabRptresult::getSampleNo, lmiEntry.getSampleNo());
        _labrptresultmapper.eq(LabRptresult::getRptGroup, lmiEntry.getRptGroup());
        _labrptresultmapper.eq(LabRptresult::getSampleda, lmiEntry.getSampleda());
        _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
        //模板
        if (CollectionUtils.isNotEmpty(templateIds)) {
            LambdaQueryWrapper<LabTemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplateDetail::getDelFlag, 0).in(LabTemplateDetail::getTemplateId, templateIds);//p -> templateIds.contains(p.getTemplateId()));
            List<LabTemplateDetail> labTemplateDetails = labTemplateDetailMapper.selectList(queryWrapper);
            for (LabTemplateDetail labTemplateDetail : labTemplateDetails) {
                /*待插入集合中中已有，直接跳过*/
                List<LabRptresult> _lst1 = list.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
                if (!_lst1.isEmpty()) {
                    continue;
                }
                LabRptresult labRptresult = new LabRptresult();
                labRptresult.setSampleda(params.getSampleda());
                labRptresult.setRptGroup(params.getRptGroup());
                labRptresult.setSampleNo(params.getSampleNo());
                labRptresult.setMaininfoId(params.getMaininfoId());
                labRptresult.setItemNo(labTemplateDetail.getItemNo());
                labRptresult.setItemNa(labTemplateDetail.getItemNa());
                labRptresult.setTestResult(labTemplateDetail.getRptResult());
                labRptresult.setDisplayOrder(labTemplateDetail.getSeq());
                if (!rptresultlist.isEmpty()) {
                    List<LabRptresult> _lst = rptresultlist.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
                    if (_lst.isEmpty()) {
                        list.add(labRptresult);
                    }
                } else {
                    list.add(labRptresult);
                }
            }

        }

        //申请项目对照报告项目
        if (StringUtils.isNotBlank(params.getReqNo())) {
            String sqxmdzbgxm = "";
            try {
                //扫码上机时是否带出申请项目对照的报告项目
                SysParamParam sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("smsjdcsqxmdzbgxm");
                sysp2.setClassifyCode(params.getRptGroup());
                List<SysParamFieldValueDto> sqxmdzbgxmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                sqxmdzbgxm = sqxmdzbgxmLst.size() <= 0 ? "" : sqxmdzbgxmLst.get(0).getValue();
            } catch (Exception exception) {
                sqxmdzbgxm = "";
            }
            //1是 0否
            if (StringUtils.isNotBlank(sqxmdzbgxm) && sqxmdzbgxm.equals("1")) {
                //根据申请编码 找到申请项目明细
                MPJLambdaWrapper<LabItemDict> queryWrapper1 = new MPJLambdaWrapper<>();
                queryWrapper1.distinct().selectAll(LabItemDict.class).selectAs("fee", LabFeeItem::getFeeCode, LabItemDict::getFeeItemCode).selectAs("fee", LabFeeItem::getFeeName, LabItemDict::getFeeItemName).leftJoin(LabFeeitemVsItemDict.class, "dict", p -> p.eq(LabFeeitemVsItemDict::getItemNo, LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getRptGroup, LabItemDict::getRptGroup)).leftJoin(LabFeeItem.class, "fee", p -> p.eq(LabFeeItem::getFeeCode, LabFeeitemVsItemDict::getFeeCode)).leftJoin(LabReqdetail.class, "detail", p -> p.eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode)).eq(LabItemDict::getDelFlag, 0).eq(LabFeeitemVsItemDict::getDelFlag, 0).eq(LabFeeItem::getDelFlag, 0).eq(LabReqdetail::getDelFlag, 0).eq(LabFeeitemVsItemDict::getRptGroup, params.getRptGroup()).eq(LabReqdetail::getReqNo, params.getReqNo());
                List<LabItemDict> itemDictList = labItemDictMapper.selectList(queryWrapper1);
                if (!itemDictList.isEmpty()) {
                    //提取后项目默认值
                    String tqhxmmrz = "";
                    try {
                        //扫码上机时是否带出申请项目对照的报告项目
                        SysParamParam sysp2 = new SysParamParam();
                        sysp2.setParamCode("bgdyxtcs");
                        sysp2.setField("tqhxmmrz");
                        sysp2.setClassifyCode(params.getRptGroup());
                        List<SysParamFieldValueDto> sqxmdzbgxmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                        tqhxmmrz = sqxmdzbgxmLst.size() <= 0 ? "" : sqxmdzbgxmLst.get(0).getValue();
                    } catch (Exception exception) {
                        tqhxmmrz = "";
                    }

                    for (LabItemDict itemDict : itemDictList) {
                        /*待插入集合中中已有，直接跳过*/
                        List<LabRptresult> _lst1 = list.stream().filter(p -> p.getItemNo().equals(itemDict.getItemNo())).collect(Collectors.toList());
                        if (!_lst1.isEmpty()) {
                            continue;
                        }
                        LabRptresult labRptresult = new LabRptresult();
                        labRptresult.setSampleda(params.getSampleda());
                        labRptresult.setRptGroup(params.getRptGroup());
                        labRptresult.setSampleNo(params.getSampleNo());
                        labRptresult.setMaininfoId(params.getMaininfoId());
                        labRptresult.setItemNo(itemDict.getItemNo());
                        labRptresult.setItemNa(itemDict.getItemNa());
                        labRptresult.setFeeCode(itemDict.getFeeItemCode());
                        labRptresult.setFeeName(itemDict.getFeeItemName());

                        if (StringUtils.isNotBlank(itemDict.getDefaultVal())) {
                            labRptresult.setTestResult(itemDict.getDefaultVal());
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue1())) {
                            labRptresult.setTestResult(itemDict.getDefValue1());
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue2())) {
                            labRptresult.setTestResult(itemDict.getDefValue2());
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue3())) {
                            labRptresult.setTestResult(itemDict.getDefValue3());
                        } else if (StringUtils.isNotBlank(tqhxmmrz)) {
                            labRptresult.setTestResult(tqhxmmrz);
                        }
                        if (itemDict.getSeq() != null) {
                            labRptresult.setDisplayOrder(String.valueOf(itemDict.getSeq()));
                        }
                        if (!rptresultlist.isEmpty()) {
                            List<LabRptresult> _lst = rptresultlist.stream().filter(p -> p.getItemNo().equals(itemDict.getItemNo())).collect(Collectors.toList());
                            if (_lst.isEmpty()) {
                                list.add(labRptresult);
                            }
                        } else {
                            list.add(labRptresult);
                        }
                    }
                }

            }
        }

        boolean b = labRptresultService.saveBatch(list);
        if (b) {
            return Result.succ(1, "添加成功", lmiEntry);
        } else {
            return Result.fail("添加失败");
        }

    }

    @Override
    public Result getImgRptGroupTree() {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);

        List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(lambdaQueryWrapper);

        List<Map> iList = new ArrayList<>();

        for (LabRptGroup labRptGroup : labRptGroups) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", labRptGroup.getId());
            map.put("name", labRptGroup.getRptGroupName());
            map.put("code", labRptGroup.getRptGroup());
            map.put("workGroup", labRptGroup.getWorkGroup());
            map.put("isSearch", "0");
            iList.add(map);
        }
        List<String> classList = labRptGroups.stream().map(LabRptGroup::getWorkGroup).distinct().collect(Collectors.toList());
        //查字典
        List<Map<String, Object>> yqdllist = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();

        yqdllist = yqdllist.stream().filter(a -> a.get("name").equals("图文报告")).collect(Collectors.toList());

        List<Map> returnList = new ArrayList<>();
        for (int i = 0; i < classList.size(); i++) {
            String code = classList.get(i);

            List<Map<String, Object>> arr = yqdllist.stream().filter(a -> a.get("code").equals(code)).collect(Collectors.toList());
            if (arr.size() == 0) {
                continue;
            }
            List<Map> arr1 = iList.stream().filter(is -> is.get("workGroup") != null && is.get("workGroup").equals(code)).collect(Collectors.toList());

            Map<String, Object> map = new HashMap();
            map.put("id", i + 1);
            map.put("code", code);
            map.put("name", yqdllist.isEmpty() ? "" : arr.isEmpty() ? "" : arr.get(0).get("name"));
            try {
                map.put("sx", yqdllist.isEmpty() ? "" : arr.isEmpty() ? "" : Integer.valueOf(String.valueOf(arr.get(0).get("sx"))));
            } catch (Exception e) {
                map.put("sx", 0);
            }
            map.put("children", arr1.isEmpty() ? new ArrayList<>() : arr1);
            map.put("isSearch", "1");
            returnList.add(map);
        }
        List<Map> newReturnList = returnList.stream().sorted(Comparator.comparing(l -> Integer.valueOf(String.valueOf(l.get("sx"))), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return Result.succ(1, "查询成功", newReturnList);
    }


    /**
     * @param params
     * @return
     */
    @Override
    public List<LabRptresult> batchDefItemDictAndTemplate(TemplateParams params) {
        // //没有上机记录，先创建上机记录
        // LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, params.getRptGroup());
        // lambdaQueryWrapper.eq(LabMaininfo::getSampleda, params.getSampleda());
        // lambdaQueryWrapper.eq(LabMaininfo::getSampleNo, params.getSampleNo());
        // lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        // if (!BeanUtil.isEmpty(params.getMaininfoId())) {
        //     lambdaQueryWrapper.eq(LabMaininfo::getId, params.getMaininfoId());
        // }
        //
        // //查询记录
        // List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
        // LabMaininfo lmiEntry = null;
        // if (labMainInfoList.isEmpty()) {
        //     AddLabMaininfo labmi = new AddLabMaininfo();
        //     labmi.setRptGroup(params.getRptGroup());
        //     labmi.setSampleda(params.getSampleda());
        //     labmi.setSampleNo(params.getSampleNo());
        //     try {
        //         Result r = labMaininfoService.insertMaininfoByReqNo(labmi);
        //         Integer c = (Integer) r.getStatus().get("code");
        //         if (!c.equals(1)) {
        //             return Result.fail("新增检验记录失败");
        //         }
        //         lmiEntry = (LabMaininfo) r.getData();
        //     } catch (Exception e) {
        //         //TODO
        //     }
        // } else {
        //     lmiEntry = (LabMaininfo) labMainInfoList.get(0);
        // }
        //
        // if (BeanUtil.isEmpty(lmiEntry)) {
        //     return Result.fail("没有要操作的检验记录");
        // }
        //
        // if (BeanUtil.isEmpty(params.getMaininfoId())) {
        //     params.setMaininfoId(lmiEntry.getId());
        // }

        List<String> templateIds = new ArrayList<>();
        if (!BeanUtil.isEmpty(params.getTemplateId())) {
            templateIds.add(params.getTemplateId());
        } else {
            LambdaQueryWrapper<LabTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplate::getDelFlag, 0).eq(LabTemplate::getRptGroup, params.getRptGroup()).eq(LabTemplate::getIsAutoApply, "1");
            List<LabTemplate> labTemplates = labTemplateMapper.selectList(queryWrapper);
            if (!labTemplates.isEmpty()) {
                for (LabTemplate m : labTemplates) {
                    templateIds.add(m.getId());
                }
            }
        }

        if (templateIds.isEmpty() && StringUtils.isBlank(params.getReqNo())) {
            // return Result.succ("添加成功");
            return null;
        }
        List<LabRptresult> list = new ArrayList<>();

        // LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
        // _labrptresultmapper.eq(LabRptresult::getMaininfoId, lmiEntry.getId());
        // _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);


        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
        // _labrptresultmapper.eq(LabRptresult::getMaininfoId, lmiEntry.getId());
        _labrptresultmapper.eq(LabRptresult::getRptGroup, params.getRptGroup())
                .eq(LabRptresult::getSampleda, params.getSampleda())
                .eq(LabRptresult::getSampleNo, params.getSampleNo())
                .eq(LabRptresult::getDelFlag, 0);

        List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
        //模板
        if (CollectionUtils.isNotEmpty(templateIds)) {
            LambdaQueryWrapper<LabTemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabTemplateDetail::getDelFlag, 0).in(LabTemplateDetail::getTemplateId, templateIds);//p -> templateIds.contains(p.getTemplateId()));
            List<LabTemplateDetail> labTemplateDetails = labTemplateDetailMapper.selectList(queryWrapper);
            for (LabTemplateDetail labTemplateDetail : labTemplateDetails) {
                /*待插入集合中中已有，直接跳过*/
                List<LabRptresult> _lst1 = list.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
                if (!_lst1.isEmpty()) {
                    continue;
                }
                LabRptresult labRptresult = new LabRptresult();
                labRptresult.setSampleda(params.getSampleda());
                labRptresult.setRptGroup(params.getRptGroup());
                labRptresult.setSampleNo(params.getSampleNo());
                labRptresult.setMaininfoId(params.getMaininfoId());
                labRptresult.setItemNo(labTemplateDetail.getItemNo());
                labRptresult.setItemNa(labTemplateDetail.getItemNa());
                labRptresult.setTestResult(labTemplateDetail.getRptResult());
                labRptresult.setDisplayOrder(labTemplateDetail.getSeq());
                if (!rptresultlist.isEmpty()) {
                    List<LabRptresult> _lst = rptresultlist.stream().filter(p -> p.getItemNo().equals(labTemplateDetail.getItemNo())).collect(Collectors.toList());
                    if (_lst.isEmpty()) {
                        list.add(labRptresult);
                    }
                } else {
                    list.add(labRptresult);
                }
            }

        }

        //申请项目对照报告项目
        if (StringUtils.isNotBlank(params.getReqNo())) {
            String sqxmdzbgxm = "";
            try {
                //扫码上机时是否带出申请项目对照的报告项目
                SysParamParam sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("smsjdcsqxmdzbgxm");
                sysp2.setClassifyCode(params.getRptGroup());
                List<SysParamFieldValueDto> sqxmdzbgxmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                sqxmdzbgxm = sqxmdzbgxmLst.size() <= 0 ? "" : sqxmdzbgxmLst.get(0).getValue();
            } catch (Exception exception) {
                sqxmdzbgxm = "";
            }
            //1是 0否
            if (StringUtils.isNotBlank(sqxmdzbgxm) && sqxmdzbgxm.equals("1")) {
                //根据申请编码 找到申请项目明细
                MPJLambdaWrapper<LabItemDict> queryWrapper1 = new MPJLambdaWrapper<>();
                queryWrapper1.distinct().selectAll(LabItemDict.class).selectAs("fee", LabFeeItem::getFeeCode, LabItemDict::getFeeItemCode).selectAs("fee", LabFeeItem::getFeeName, LabItemDict::getFeeItemName).leftJoin(LabFeeitemVsItemDict.class, "dict", p -> p.eq(LabFeeitemVsItemDict::getItemNo, LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getRptGroup, LabItemDict::getRptGroup)).leftJoin(LabFeeItem.class, "fee", p -> p.eq(LabFeeItem::getFeeCode, LabFeeitemVsItemDict::getFeeCode)).leftJoin(LabReqdetail.class, "detail", p -> p.eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode)).eq(LabItemDict::getDelFlag, 0).eq(LabFeeitemVsItemDict::getDelFlag, 0).eq(LabFeeItem::getDelFlag, 0).eq(LabReqdetail::getDelFlag, 0).eq(LabFeeitemVsItemDict::getRptGroup, params.getRptGroup()).eq(LabReqdetail::getReqNo, params.getReqNo());
                List<LabItemDict> itemDictList = labItemDictMapper.selectList(queryWrapper1);
                if (!itemDictList.isEmpty()) {
                    //提取后项目默认值
                    String tqhxmmrz = "";
                    try {
                        //扫码上机时是否带出申请项目对照的报告项目
                        SysParamParam sysp2 = new SysParamParam();
                        sysp2.setParamCode("bgdyxtcs");
                        sysp2.setField("tqhxmmrz");
                        sysp2.setClassifyCode(params.getRptGroup());
                        List<SysParamFieldValueDto> sqxmdzbgxmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                        tqhxmmrz = sqxmdzbgxmLst.size() <= 0 ? "" : sqxmdzbgxmLst.get(0).getValue();
                    } catch (Exception exception) {
                        tqhxmmrz = "";
                    }

                    for (LabItemDict itemDict : itemDictList) {
                        /*待插入集合中中已有，直接跳过*/
                        List<LabRptresult> _lst1 = list.stream().filter(p -> p.getItemNo().equals(itemDict.getItemNo())).collect(Collectors.toList());
                        if (!_lst1.isEmpty()) {
                            continue;
                        }
                        LabRptresult labRptresult = new LabRptresult();
                        labRptresult.setSampleda(params.getSampleda());
                        labRptresult.setRptGroup(params.getRptGroup());
                        labRptresult.setSampleNo(params.getSampleNo());
                        labRptresult.setMaininfoId(params.getMaininfoId());
                        labRptresult.setItemNo(itemDict.getItemNo());
                        labRptresult.setItemNa(itemDict.getItemNa());
                        labRptresult.setFeeCode(itemDict.getFeeItemCode());
                        labRptresult.setFeeName(itemDict.getFeeItemName());

                        if (StringUtils.isNotBlank(itemDict.getDefaultVal())) {
                            labRptresult.setTestResult(itemDict.getDefaultVal());
                            labRptresult.setIsResult(1);
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue1())) {
                            labRptresult.setTestResult(itemDict.getDefValue1());
                            labRptresult.setIsResult(1);
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue2())) {
                            labRptresult.setTestResult(itemDict.getDefValue2());
                            labRptresult.setIsResult(1);
                        } else if (StringUtils.isNotBlank(itemDict.getDefValue3())) {
                            labRptresult.setTestResult(itemDict.getDefValue3());
                            labRptresult.setIsResult(1);
                        } else if (StringUtils.isNotBlank(tqhxmmrz)) {
                            labRptresult.setTestResult(tqhxmmrz);
                        }
                        if (itemDict.getSeq() != null) {
                            labRptresult.setDisplayOrder(String.valueOf(itemDict.getSeq()));
                        }
                        if (!rptresultlist.isEmpty()) {
                            List<LabRptresult> _lst = rptresultlist.stream().filter(p -> p.getItemNo().equals(itemDict.getItemNo())).collect(Collectors.toList());
                            if (_lst.isEmpty()) {
                                list.add(labRptresult);
                            }
                        } else {
                            list.add(labRptresult);
                        }
                    }
                }

            }
        }

        return list;

        //boolean b = labRptresultService.saveBatch(list);
        // if (b) {
        //     return Result.succ(1, "添加成功", lmiEntry);
        // } else {
        //     return Result.fail("添加失败");
        // }

    }

}
